<?php
class NewsController extends Pidguin_Controller_Public_Action
{	
	public function indexAction()
	{
		$userGroups = Pidguin_Client::getInstance()->getClient()->groups;
		$userGroupsId = array();
		foreach ($userGroups as $group) {
		    array_push($userGroupsId, $group->id);
		}
		$cacheManager = Zend_Registry::get('cache');
		$cache = $cacheManager->getCache('file');
		if (!$news = $cache->load('Pidguin_DB_News')) {
			$news = Model_News::getInstance()->fetchAll(Model_News::getInstance()->select()->order('created DESC'));
			$cache->save($news, 'Pidguin_DB_News');
		}
		$news->setTable(Model_News::getInstance());
		$viewNews = array();
		$i = 0;
		if (count($news) > 0) {
		    foreach ($news as $n) {
		        $newsGroup = $n->findDependentRowset('Model_NewsGroup');
		        if (count($newsGroup) <= 0) {
		            $viewNews[$i] = $n;
		            $i++;
		            continue;
		        }
		        foreach ($userGroups as $ug) {
		            if ($ug->id == 1 || $ug->id == 4) {
		                $viewNews[$i] = $n;
		                break;
		            }
		        }
		        if (!empty($viewNews[$i])) {
		            $i++;
		            continue;
		        }
		        foreach ($newsGroup as $ng) {
		            $searchToGroup = array_search($ng->group_id, $userGroupsId);
		            if (false === $searchToGroup) {
		                continue;
		            }
		            $viewNews[$i] = $n;
		            break;
		        }
		        if (!empty($viewNews[$i])) {
		            $i++;
		            continue;
		        }
		    }
		}
		$paginator = new Zend_Paginator(new Zend_Paginator_Adapter_Array($viewNews));
		$paginator->setCurrentPageNumber($this->_getParam('page'));
		$this->view->paginator = $paginator;
	}
	
	public function getAction()
	{
	    if (!$this->_getParam('key')) {
	        $this->_redirect('/news');
	    }
	    
	    $modelNews = Model_News::getInstance();
	    $select = $modelNews->select()->where(
	        Model_News::getDefaultAdapter()->quoteInto('url_key = ?', $this->_getParam('key'))
	    )->limit(1);
	    $newsRow = $modelNews->fetchRow($select);
	    
	    if (!$newsRow) {
	        throw new Zend_Controller_Action_Exception('News not found');
	    }
	    
	    $userGroups = Pidguin_Client::getInstance()->getClient()->groups;
		$userGroupsId = array();
		$viewNews = 0;
		
		foreach ($userGroups as $group) {
		    array_push($userGroupsId, $group->id);
		    if ($group->id == 1 || $group->id == 4) {
		        $viewNews = 1;
		    }
		}
		
		if ($viewNews == 0) {
		    $newsGroup = $newsRow->findDependentRowset('Model_NewsGroup');
		
		    if (count($newsGroup) <= 0) {
		        $viewNews = 1;
		    } else {
		    
		        foreach ($newsGroup as $ng) {
                    $searchToGroup = array_search($ng->group_id, $userGroupsId);
                    
                    if (false === $searchToGroup) {
                        continue;
                    }
                    $viewNews = 1;
                    break;
                }
            }
        }
        
        if ($viewNews == 0) {
           throw new Zend_Controller_Action_Exception('News not found');
        }
        $this->view->headTitle($newsRow->title);
        $this->view->news = $newsRow;
	}
	
	public function commentAddAcceptCaptchaAction()
	{
		if (!$this->getRequest()->isXmlHttpRequest()) {
			throw new Zend_Controller_Action_Exception('Not ajax');
		}
		
		if ($this->getRequest()->isPost()) {
			$f = new Application_Form_News_Comment_Captcha();
			if (!$f->isValid($_POST)) {
				$nc = new Application_Form_News_Comment_Captcha();
				$this->_helper->json(array('form' => $nc->render()));
			}
		}
		$this->_helper->json($this->_getParam('captcha'));
		$this->_disableView();
	}
	
	public function commentAddAction()
	{
		if (!$this->getRequest()->isXmlHttpRequest()) {
			throw new Zend_Controller_Action_Exception('Not ajax');
		}
		
		if (!$this->_getParam('news_id')) {
			throw new Zend_Controller_Action_Exception('News ID is not set');
		}
		
		$user = Pidguin_Client::getInstance()->getClient()->user;
		if ($user->id == 1) {
			if (!$this->_getParam('name')) {
				throw new Zend_Controller_Action_Exception('User name is not set');
			}
			
			if ($this->_getParam('captcha')) {
				$f = new Application_Form_News_Comment_Captcha();
				if (!$f->isValid($_POST)) {
					$nc = new Application_Form_News_Comment_Captcha();
					$this->_helper->json(array('form' => $nc->render()));
				}
			} else {
				$captcha_form = new Application_Form_News_Comment_Captcha();
				$captcha_form->addElement('hidden', 'name', array('value' => $this->_getParam('name')));
				$captcha_form->addElement('hidden', 'text', array('value' => $this->_getParam('text')));
				$captcha_form->addElement('hidden', 'news_id', array('value' => $this->_getParam('news_id')));
				$this->_helper->json(array(
					'captcha_form' => $captcha_form->render()
				));
			}
		}
		
		$newsSelect = Model_News::getInstance()->select()->where(
			Model_News::getDefaultAdapter()->quoteInto('id = ?', $this->_getParam('news_id'))
		);
		$newsRow = Model_News::getInstance()->fetchRow($newsSelect);
		
		if (!$newsRow) {
			$this->_helper->json(array(
					'error' => 'News not found'
				));
		}
		
		$userGroups = Pidguin_Client::getInstance()->getClient()->groups;
		$userGroupsId = array();
		$viewNews = 0;
		
		foreach ($userGroups as $group) {
		    array_push($userGroupsId, $group->id);
		    if ($group->id == 1 || $group->id == 4) {
		        $viewNews = 1;
		    }
		}
		
		if ($viewNews == 0) {
		    $newsGroup = $newsRow->findDependentRowset('Model_NewsGroup');
		
		    if (count($newsGroup) <= 0) {
		        $viewNews = 1;
		    } else {
		    
		        foreach ($newsGroup as $ng) {
                    $searchToGroup = array_search($ng->group_id, $userGroupsId);
                    
                    if (false === $searchToGroup) {
                        continue;
                    }
                    $viewNews = 1;
                    break;
                }
            }
        }
        
        if ($viewNews == 0) {
			$this->_helper->json(array(
					'error' => 'News not found'
				));
        }
		
		$commentRow = Model_NewsComments::getInstance()->createRow();
		$commentRow->news_id = $newsRow->id;
		$commentRow->author_id = $user->id;
		$commentRow->name = ($user->id == 1) ? $this->_getParam('name') : '';
		$commentRow->text = strip_tags($this->_getParam('text'), '<a>');
		$commentRow->created = date('Y-m-d H:i:s');
		$commentRow->save();
		$date = new Zend_Date($commentRow->created, false, Pidguin_Application::getInstance()->getLocale());
		$this->_helper->json(array(
			'comment' => array(
				'id' => $commentRow->id,
				'name' => ($user->id == 1) ? $this->_getParam('name') : $user->name,
				'text' => $commentRow->text,
				'created' => $date->toString('dd MMMM в HH:mm')
			)
		));
	}
}
